#include "gt_file.h"
#include "gt_theme.h"
#include <cstring>
#include <linux/limits.h>
#include <ncurses.h>

// ok
static void *get_file(entry_t *entry, entry_type_t type) {
  if (type == FILE_ENTRY)
    return container_of(entry, gt_file_t, entry);

  return NULL;
}

// ok
static char *remove_double(char *initial, char c, char *final) {
  int len = strlen(initial);
  int i, j;
  for (i = 0, j = 0; i < len; j++) {
    if (initial[i] != c) {
      final[j] = initial[i];
      i++;
    } else {
      final[j] = initial[i];
      if (initial[i + 1] == c)
        i = i + 2;
      else
        i++;
    }
  }

  final[j] = '\0';
  return final;
}

// ok
static void format_path(char *src, char *dest) {
  if (strncmp(src, "./", 2) == 0)
    remove_double(src + 2, '/', dest);
  else
    remove_double(src, '/', dest);
}

// ok
entry_vtable file_vtable = {display_file, is_file_selectable, free_file,
                            get_file};
// ok
entry_t *create_file(result_t *result, char *file) {
  int len = strlen(file) + 1;
  gt_file_t *new_file;
  new_file = (gt_file_t *)calloc(1, sizeof(gt_file_t) + len);

  format_path(file, new_file->entry.data);
  new_file->entry.vtable = &file_vtable;
  result->nbentry++;

  if (result->entries)
    result->entries->next = &new_file->entry;
  else
    result->start = &new_file->entry;

  return &new_file->entry;
}

// ok
void display_file(entry_t *entry, search_t *search, int y,
                  int is_cursor_on_entry) {
  int crop = COLS;
  char cropped_line[PATH_MAX] = "";
  strncpy(cropped_line, entry->data, crop);

  move(y, 0);
  clrtoeol();

  attron(A_BOLD);
  attron(COLOR_PAIR(COLOR_FILE));
  mvprintw(y, 0, "%s", cropped_line);

  attroff(A_BOLD);
}

// ok
int is_file_selectable(entry_t *entry) { return false; }

// ok
void free_file(entry_t *entry) {
  gt_file_t *ptr = container_of(entry, gt_file_t, entry);
  free(ptr);
}

